<template>
    <view class="container">
        <view class="body">
            <!-- 搜索条 -->
            <up-sticky bgColor="#fff">
                <view class="search">
                    <up-search placeholder="输入关键字" v-model="searchWord" @search="keywordSearch" :showAction="false" />
                </view>
            </up-sticky>

            <!-- 修改后的日期选择按钮，直接显示日期范围 -->
            <view class="date-selector">
                <!-- <u-button type="primary" size="mini" @click="showCalendar = true" plain="true" shape="circle"
                    :customStyle="dateButtonStyle">
                    {{ dateButtonText }}
                </u-button> -->


                <picker mode="date" :value="spotCheckDate" :start="pickMinDate" :end="pickMaxDate"
                    @change="datePickerChange">
                    <u-button type="primary" size="mini" plain="true" shape="circle" :customStyle="dateButtonStyle">
                        {{ spotCheckDate ? '点检日期：' + spotCheckDate : '选择点检日期' }}
                    </u-button>
                </picker>


            </view>

            <!-- 日期选择弹窗 -->
            <!-- <u-calendar :show="showCalendar" mode="range" @confirm="onCalendarConfirm" @close="showCalendar = false" /> -->

            <!-- 设备列表（分页加载） -->
            <view class="task-list">
                <u-collapse v-model="activeCollapseKeys" :accordion="false">
                    <u-collapse-item v-for="(item, index) in ListData" :key="item.id"
                        :title="`点检时间：${item.datelist} - ${item.week}`" :name="item.id">
                        <!-- 折叠面板内容：反馈明细 -->
                        <view class="detail-list" v-for="(detail, dIndex) in item.details" :key="dIndex">
                            <view class="detail-row">
                                <text class="label">内容：</text>
                                <text class="value">{{ detail.content }}</text>
                            </view>
                            <view class="detail-row" v-if="detail.description">
                                <text class="label">异常描述：</text>
                                <text class="value">{{ detail.description }}</text>
                            </view>
                            <view class="detail-row" v-if="detail.reason">
                                <text class="label">异常原因：</text>
                                <text class="value">{{ detail.reason }}</text>
                            </view>
                            <view class="detail-row" v-if="detail.type">
                                <text class="label">异常类型：</text>
                                <text class="value">{{ detail.type }}</text>
                            </view>
                            <view class="detail-row">
                                <text class="label">状态：</text>
                                <text class="value" :style="{ color: detail.status === '异常' ? 'red' : 'green' }">
                                    {{ detail.status }}
                                </text>
                            </view>
                            <view class="divider"></view>
                        </view>
                    </u-collapse-item>
                </u-collapse>

            </view>

            <!-- 加载更多提示 -->
            <view class="load-more" v-if="ListData.length < total">
                <u-loadmore status="loading" />
            </view>
            <view class="load-more" v-else-if="ListData.length > 0">
                <u-loadmore status="nomore" />
            </view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            deviceId: '',
            ListData: [],
            searchWord: '',
            pageNum: 1,
            pageSize: 20,
            total: 0,
            beginTime: '',
            endTime: '',
            // showCalendar: false,
            dateRange: {
                start: '',
                end: ''
            },
            searchParams: {},
            activeCollapseKeys: [],
            collapseKeyVersion: 0,
            spotCheckDate: '',          // 当前选择的日期
            pickMinDate: '2020-01-01',  // 可选起始日期（可根据实际情况修改）
            pickMaxDate: '2030-12-31',  // 可选截止日期

        };
    },
    computed: {
        // 按钮显示文本
        dateButtonText() {
            if (this.dateRange.start) {
                return this.dateRange.start;
            }
            return '选择点检日期';
        },
        // 按钮样式
        // dateButtonStyle() {
        //     return {
        //         height: '30px',
        //         // 如果有选择日期，调整内边距让文字显示更完整
        //         padding: this.dateRange.start ? '0 10px' : '0 20px',
        //         fontSize: '14px'  // 增加字体大小
        //     };
        // }



        dateButtonStyle() {
            return {
                height: '30px',
                padding: '0 10px',
                fontSize: '14px'
            };
        }

    },
    onLoad(options) {
        this.deviceId = options.deviceId;
        this.getInspectionInfo();

    },
    methods: {
        // 日期范围选择确认
        onCalendarConfirm(e) {
            const startDate = e[0];
            const endDate = e[e.length - 1]; // 获取数组的最后一个元素作为结束日期
            this.dateRange = {
                start: startDate,
                end: endDate
            };
            this.beginTime = startDate;
            this.endTime = endDate;
            this.showCalendar = false;
            // 日期选择后自动触发搜索
            this.pageNum = 1;
            this.getInspectionInfo();
        },

        // 其他方法保持不变...
        async keywordSearch() {
            this.pageNum = 1;
            this.getInspectionInfo();
        },

        async getInspectionInfo() {
            const currentParams = {
                sbId: this.deviceId,
                keyword: this.searchWord,
                beginTime: this.beginTime,
                endTime: this.endTime
            };

            if (JSON.stringify(currentParams) !== JSON.stringify(this.searchParams)) {
                this.pageNum = 1;
                this.ListData = [];
            }

            this.searchParams = { ...currentParams };

            const params = {
                ...currentParams,
                pageNum: this.pageNum,
                pageSize: this.pageSize
            };

            try {
                const res = await this.$commonUnits.postRequest(
                    "sbby.sbtzmobile.sbdjHistory.mobile",
                    params
                );
                this.total = res.res.total || 0; // ✅ 必须写上

                if (!res.res.data || Object.keys(res.res.data).length === 0) {

                    if (this.pageNum === 1) {
                        this.ListData = [];
                    }
                } else {
                    const pageData = Object.keys(res.res.data).map(key => {
                        const records = res.res.data[key];
                        if (!records || records.length === 0) return null;

                        const first = records[0]; // 公共信息
                        const detailList = records.map(detail => {
                            return {
                                content: detail.SPOTCHECKCONTENT,
                                description: detail.ABNORMALDESCRIPTION,
                                reason: detail.ABNORMALREASON,
                                type: detail.ABNORMALTYPE,
                                status: detail.WHETHERNORMAL === '1' ? '正常' : '异常'
                            };
                        });

                        return {
                            id: key,
                            week: first.WEEK,
                            datelist: first.DATELIST,
                            details: detailList
                        };
                    }).filter(item => item !== null);

                    // ✅ 改这里，分页时追加
                    if (this.pageNum === 1) {
                        this.ListData = pageData;
                        // 设置默认展开项
                        this.setDefaultCollapse();
                    } else {
                        this.ListData = this.ListData.concat(pageData);
                    }

                }
            } catch (err) {
                uni.showToast({
                    title: '数据加载失败',
                    icon: 'none'
                });
            }
        },

        // 卡片默认展开
        setDefaultCollapse() {
            if (this.ListData.length > 0) {
                const firstId = String(this.ListData[0].id);
                this.$nextTick(() => {
                    this.activeCollapseKeys = [firstId];
                    this.collapseKeyVersion++; // 触发重渲染
                });
            }
        },


        dataInfo(item) {
            uni.navigateTo({
                url: `/pageTwo/pages/record/detail?deviceId=${item.plandateid}`
            });
        },

        datePickerChange(e) {
            const selectedDate = e.detail.value;
            this.spotCheckDate = selectedDate;
            this.beginTime = selectedDate;
            this.endTime = selectedDate;

            this.pageNum = 1;
            this.getInspectionInfo(); // ✅ 触发搜索
        }
    },
    onReachBottom() {
        if (this.ListData.length >= this.total) return;
        this.pageNum++;
        this.getInspectionInfo();
    },

    // selectDate() {
    //     const that = this;
    //     uni.showDatePicker({
    //         type: 'date',
    //         success(res) {
    //             const selectedDate = res.value; // 结果为 2025-06-12 这种格式

    //             that.dateRange = {
    //                 start: selectedDate,
    //                 end: selectedDate
    //             };
    //             that.beginTime = selectedDate;
    //             that.endTime = selectedDate;

    //             that.pageNum = 1;
    //             that.getInspectionInfo(); // 查询该日数据
    //         },
    //         fail(err) {
    //             console.log("选择取消", err);
    //         }
    //     });
    // }




}
</script>

<style scoped>
/* 调整日期选择器样式 */
.date-selector {
    padding: 10px 15px;
    background-color: #fff;
}

/* 新增样式 */

.date-range-text {
    margin-left: 10px;
    font-size: 14px;
    color: #666;
}

.detail-row {
    display: flex;
    margin-bottom: 6px;
}

.label {
    width: 80px;
    font-weight: bold;
}

.value {
    flex: 1;
}

.divider {
    height: 1px;
    background-color: #eee;
    margin: 10px 0;
}

.date-selector {
    display: flex;
    align-items: center;
    justify-content: center;
    /* ✅ 加上这句即可居中 */
    padding: 10px 15px;
    background-color: #fff;
}
</style>
<style src="./record.css"></style>